package com.GlobalPaint.app.ui.HTML;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;

import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.EventBusben;
import com.GlobalPaint.app.ui.Login.Login;
import com.GlobalPaint.app.utils.CommUtility;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.utils.FirstEvent;
import com.blankj.utilcode.utils.SPUtils;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebBackForwardList;
import com.tencent.smtt.sdk.WebHistoryItem;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.greenrobot.eventbus.EventBus;

public class PublishHtml extends AppCompatActivity {
    private WebView wb_publish;
    private ProgressDialog progressDialog;
    private String find;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_html);
        find=getIntent().getStringExtra("flid");
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);

            getWindow().setFormat(PixelFormat.TRANSLUCENT);  //（这个对宿主没什么影响，建议声明）
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        }
            wb_publish = (WebView) findViewById(R.id.wb_publish);
            progressDialog = CommUtility.openProgressDialog(PublishHtml.this,
                    progressDialog, "正在加载中...");
            wb_publish.setWebViewClient(new WebViewClient() {

                @Override
                public void onLoadResource(WebView view, String url) {

                    if (url.equals("phone://outofdate")) {
                        SPUtils spUtils = new SPUtils(DataManager.context, "login");
                        spUtils.remove("user");
                        //退出时清除缓存
                        DataManager.lruCache = new LruCache<>(10);
                        Intent intent = new Intent(PublishHtml.this, Login.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        finish();
                    }
                }


                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    //判断url拦截事件
                    if (url.indexOf("append")!=-1) {
                        EventBus.getDefault().post(new FirstEvent("qiuzhi"));
                        finish();
                        wb_publish.clearHistory(); // 清除
                        return true;
                    } else if (url.indexOf("appLoginOut")!=-1) {
                        SPUtils spUtils = new SPUtils(DataManager.context, "login");
                        spUtils.remove("user");
                        //退出时清除缓存
                        DataManager.lruCache = new LruCache<>(10);
                        Intent intent = new Intent(PublishHtml.this, Login.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        finish();
                        return true;
                    }   else if(url.indexOf("zhaoGongRefresh")!=-1){
                        EventBusben baseMessage = new EventBusben("zhaogong");
                        EventBus.getDefault().post(baseMessage);
                        finish();
                        return true;
                    }else if(url.indexOf("qiuZhiRefresh")!=-1){
                        EventBusben baseMessage = new EventBusben("qiuzhi");
                        EventBus.getDefault().post(baseMessage);
                        finish();
                        return true;
                    }else if(url.indexOf("linShiZhaoGongRefresh")!=-1){
                        EventBusben baseMessage = new EventBusben("linshi");
                        EventBus.getDefault().post(baseMessage);
                        finish();
                        return true;
                    }
                    else {
                        CommUtility.closeProgressDialog(progressDialog);
                        wb_publish.loadUrl(url);
                        return false;
                    }
                }

                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    CommUtility.closeProgressDialog(progressDialog);
                }

                //接收不到404
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    CommUtility.closeProgressDialog(progressDialog);
                }
            });

            WebSettings webSettings = wb_publish.getSettings();
            webSettings.setJavaScriptEnabled(true);
            CookieSyncManager.createInstance(this);
            CookieSyncManager.getInstance().sync();
            if(find.equals("1")){ //qiuzhi
                wb_publish.loadUrl(Constants.JASON_SERVICE_URL_H5 +"fb_qiuZhi.html?useId="
                        +DataManager.userEntity.getUserId() +
                        "&token="+DataManager.userEntity.getCookie()
                        +"&useName="+DataManager.userEntity.getUserName());
            } else if(find.equals("0")){//招工
                wb_publish.loadUrl(Constants.JASON_SERVICE_URL_H5 +"fb_zhaoGong.html?useId="
                        +DataManager.userEntity.getUserId() +
                        "&token="+DataManager.userEntity.getCookie()
                        +"&useName="+DataManager.userEntity.getUserName()+"&type=zhaoGong");
            }else if(find.equals("2")){//临时招工
                wb_publish.loadUrl(Constants.JASON_SERVICE_URL_H5 +"fb_zhaoGong.html?useId="
                        +DataManager.userEntity.getUserId() +
                        "&token="+DataManager.userEntity.getCookie()
                        +"&useName="+DataManager.userEntity.getUserName()+"&type=liShizhaoGong");
            }
        }
    private boolean canGoBack() {
        if (wb_publish.canGoBack()) {
            WebBackForwardList list = wb_publish.copyBackForwardList();
            WebHistoryItem item = list.getCurrentItem();
            System.out.println("URL: " + item.getUrl());

            if (item.getUrl().indexOf("succeed.html") >= 0) {

                finish();
                return false;
            }else if(item.getUrl().indexOf("MyLeaveDetail.html") >= 0){

                finish();
                return false;
            }
            return wb_publish.canGoBack();

        }
        finish();
        return wb_publish.canGoBack();
    }
    // Prevent the back-button from closing the app
    @Override
    public void onBackPressed() {
        if(canGoBack()) {
            wb_publish.goBack();
        } else {
            //super.onBackPressed();

            exit();
            wb_publish.clearHistory(); // 清除
        }
    }

    private long mExitTime;
    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            //     Toast.makeText(AskForLeaveActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }
}
